package com.luobr.backend.manage.websocket.disruptor;

import cn.hutool.json.JSONUtil;
import com.lmax.disruptor.WorkHandler;
import com.luobr.backend.manage.websocket.ImageEditHandler;
import com.luobr.backend.manage.websocket.model.ImageEditRequestMessage;
import com.luobr.backend.manage.websocket.model.ImageEditResponseMessage;
import com.luobr.backend.manage.websocket.model.enums.ImageEditMessageTypeEnum;
import com.luobr.backend.model.vo.user.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

@Slf4j
@Component
public class ImageEditEventConsumer implements WorkHandler<ImageEditEvent> {

    @Resource
    @Lazy
    private ImageEditHandler imageEditHandler;

    @Override
    public void onEvent(ImageEditEvent event) throws Exception {
        ImageEditRequestMessage pictureEditRequestMessage = event.getImageEditRequestMessage();
        WebSocketSession session = event.getSession();
        UserLoginVO user = event.getUser();
        Long imageId = event.getImageId();
        // 获取到消息类别
        String type = pictureEditRequestMessage.getType();
        ImageEditMessageTypeEnum imageEditMessageTypeEnum = ImageEditMessageTypeEnum.valueOf(type);
        // 调用对应的消息处理方法
        switch (imageEditMessageTypeEnum) {
            case ENTER_EDIT:
                imageEditHandler.handleEnterEditMessage(pictureEditRequestMessage, session, user, imageId);
                break;
            case EDIT_ACTION:
                imageEditHandler.handleEditActionMessage(pictureEditRequestMessage, session, user, imageId);
                break;
            case EXIT_EDIT:
                imageEditHandler.handleExitEditMessage(pictureEditRequestMessage, session, user, imageId);
                break;
            default:
                ImageEditResponseMessage imageEditResponseMessage = new ImageEditResponseMessage();
                imageEditResponseMessage.setType(ImageEditMessageTypeEnum.ERROR.getValue());
                imageEditResponseMessage.setMessage("消息类型错误");
                imageEditResponseMessage.setUser(user);
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(imageEditResponseMessage)));
        }
    }
}
